<template>
<span>
{{ dayString + '天' + hourString + ':' + minuteString + ':' + secondString
  }}
</span>
</template>
<script>
import {defineComponent, reactive} from 'vue'
export default {
  name: 'CountDown',
  data() {
    return {
      day: '',
      hour: '',
      minute: '',
      second: '',
      timer: '',
      start: false,
    }
  },
  props: {
    endTime: {
// 倒计时结束时间
      default: '2022-09-05 21:17:40'
    },
    callback: () => {
      alert(1)
    }
  },
  mounted() {
    let remainTime = new Date(this.endTime).getTime() - new Date().getTime();
    if (remainTime > 0) {
      this.day = Math.floor(remainTime / (1000 * 60 * 60 * 24))
      this.hour = Math.floor((remainTime / 1000 / 3600) % 24)
      this.minute = Math.floor((remainTime / 1000 / 60) % 60)
      this.second = Math.floor(remainTime / 1000 % 60)
      this.countDowm()
    }
  },
  methods: {
    ending() {
      this.$emit("TimeEnding");
    },
    countDowm() {
      let self = this
      clearInterval(this.timer)
      this.timer = setInterval(function () {
        if (self.hour === 0) {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59
            self.minute -= 1
          } else if (self.minute === 0 && self.second === 0) {
            if (self.day === 0) {
              self.second = 0
              self.$emit('countDowmEnd', true)
              this.start = true;
              clearInterval(self.timer)
              self.ending();
            } else {
              self.day -= 1;
              self.hour = 23;
              self.minute = 59;
              self.second = 59;
            }
          } else {
            self.second -= 1
          }
        } else {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59
            self.minute -= 1
          } else if (self.minute === 0 && self.second === 0) {
            self.hour -= 1
            self.minute = 59
            self.second = 59
          } else {
            self.second -= 1
          }
        }
      }, 1000)
    },
    formatNum(num) {
      return num < 10 ? '0' + num : '' + num;
    }
  },
  computed: {
    dayString() {
      return this.formatNum(this.day)
    },
    hourString() {
      return this.formatNum(this.hour)
    },
    minuteString() {
      return this.formatNum(this.minute)
    },
    secondString() {
      return this.formatNum(this.second)
    }
  }
}
</script>
